package com.ymatou.shop.ui.activity.buyer;

import java.lang.reflect.Field;
import java.util.Date;
import com.ymatou.shop.R;
import com.ymatou.shop.api.ApiRequest;
import com.ymatou.shop.api.ApiResponse;
import com.ymatou.shop.cache.RequestInfo;
import com.ymatou.shop.cache.exception.CacheException;
import com.ymatou.shop.model.LoginResult;
import com.ymatou.shop.model.Order;
import com.ymatou.shop.model.Product;
import com.ymatou.shop.model.ResponseMessage;
import com.ymatou.shop.ui.activity.BaseHeaderActivity;
import com.ymatou.shop.util.DialogUtil;
import com.ymatou.shop.util.GlobalUtil;
import com.ymatou.shop.util.StringUtil;
import com.ymatou.shop.util.Utils;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;

public class PayOrderActivity extends BaseHeaderActivity implements OnClickListener {

	private static final int REQUEST_ID_GET_USER_ACCOUNT_INFO = 1;
	private static final int REQUEST_ID_PAY_ORDER = 2;
	public final static String PRODUCT_KEY = "product_key";
	public final static String LOGIN_RESULT_KEY = "login_result_key";
	public final static String RED_MONEY_KEY = "red_money_key";
	private TextView redMoneyTextView, leftMoneyTextView, depositTextView2, payTotalMoneyTextView;
	private View   orderHintView, layout3, okView, payLayoutView;
	private TextView leftTimeHintView;
	private Product mProduct;
	private ToggleButton userLeftMoneyToggleButton;
	private String tradingPasswrod;
	private LoginResult mLoginResult;
	private float redMoney;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pay_order);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		getIntentData();
		setupViews();
		setData();
	}

	private void getIntentData() {
		if (getIntent() != null) {
			mProduct = (Product) getIntent().getSerializableExtra(PRODUCT_KEY);
			mLoginResult = (LoginResult) getIntent().getSerializableExtra(LOGIN_RESULT_KEY);
			redMoney = getIntent().getFloatExtra(RED_MONEY_KEY, 0);
		}
	}


	private void setData() {
		
	}

	@Override
	protected void setupViews() {
		super.setupViews();

		getTitleLeftButton().setVisibility(View.VISIBLE);
		getTitleLeftButton().setText(R.string.tab_home);
		getTitleTextView().setText(R.string.product_pay_cash);
		getTitleLeftButton().setOnClickListener(this);




		payTotalMoneyTextView = (TextView)findViewById(R.id.pay_total_money);
		payTotalMoneyTextView.setText(getString(R.string.red_money_textview2, "" + (mProduct.mPrice - redMoney)));
		
		
		leftTimeHintView = (TextView)findViewById(R.id.left_time_hint);
		
		leftTimeHandler.sendEmptyMessageDelayed(0, 10000);
		
		orderHintView = findViewById(R.id.order_hint2);
		layout3 = findViewById(R.id.layout3);
		okView = findViewById(R.id.ok_textview2);
		okView.setOnClickListener(this);
		
		
		payLayoutView = findViewById(R.id.pay_type_layout);
		
		
		userLeftMoneyToggleButton = (ToggleButton)findViewById(R.id.user_left_money);
		userLeftMoneyToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked){
					//mProduct.mDownPayment
					//mLoginResult.mAvailAmount
					//红包
					if (Float.parseFloat(mLoginResult.mAvailAmount) + Float.parseFloat(mLoginResult.mGiftAvailAmount) >= mProduct.mDownPayment){
						payLayoutView.setVisibility(View.GONE);
					}else {
						payLayoutView.setVisibility(View.VISIBLE);
					}
					
				}else {
					payLayoutView.setVisibility(View.VISIBLE);
				}
				
			}
		});

		leftTimeHintView.setVisibility(View.VISIBLE);
		orderHintView.setVisibility(View.VISIBLE);
		layout3.setVisibility(View.VISIBLE);
		okView.setVisibility(View.VISIBLE);

		redMoneyTextView = (TextView) findViewById(R.id.red_money);
		redMoneyTextView.setText("" + redMoney);

		leftMoneyTextView = (TextView) findViewById(R.id.leftcash_textview);
		leftMoneyTextView.setText(getString(R.string.user_leftcash_textview, mLoginResult.mAvailAmount));

		depositTextView2 = (TextView) findViewById(R.id.deposit2);
		depositTextView2.setText(getString(R.string.red_money_textview2, mProduct.mDownPayment));
		
	}

	private int leftTime = 5 * 60;
	
	protected Handler leftTimeHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			--leftTime;

			if (leftTime == 0 || leftTime < 0) {
			
			}
			leftTimeHintView.setText(Utils.getTimeLengthString(leftTime));
			sendEmptyMessageDelayed(0, 1000);
		}
	};


	
	private void payOrder() {
		RequestInfo request3 = ApiRequest.getAccountInfo();
		getCacheManager().register(REQUEST_ID_GET_USER_ACCOUNT_INFO, request3, this);
	}

	@Override
	public void onCacheSuccess(int requestId, RequestInfo requestInfo, Object response) {
		cancelProgressDialog();
		switch (requestId) {
		case REQUEST_ID_GET_USER_ACCOUNT_INFO:
			
			break;
		case REQUEST_ID_PAY_ORDER:
			ResponseMessage mResponseMessage = ApiResponse.saveOrder((String) response);
			if (mResponseMessage.status == 200){
				if (StringUtil.isNotEmpty(mResponseMessage.payUrl)){
					GlobalUtil.shortToast(this, mResponseMessage.payUrl);
				}else {
					GlobalUtil.shortToast(this, mResponseMessage.message);	
				}
				
			}
			break;
		default:

			break;
		}
		super.onCacheSuccess(requestId, requestInfo, response);
	}

	@Override
	public void onCacheFailed(int requestId, RequestInfo requestInfo, CacheException error) {
		super.onCacheFailed(requestId, requestInfo, error);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.title_left_button:
			onBackPressed();
			break;
		case R.id.ok_textview2:
			//判断是否使用余额 是 弹出输入支付密码 否 余额为零 判断是否使用支付宝 是    否 

			//使用红包
			
			//账户余额
			if (userLeftMoneyToggleButton.isChecked()){
				//使用余额
				useLeftMoney(v);
			}else {
				//不使用余额
			}
			break;
		default:
			break;
		}
	}
	
	private void useLeftMoney(View v){
		if (mLoginResult.mExistsTradingPassword) {
			//弹出输入密码框
			final EditText mEditText = new EditText(v.getContext());
			new AlertDialog.Builder(v.getContext()).setTitle(R.string.pay_password_text).setView(mEditText).setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					tradingPasswrod = mEditText.getText().toString();
					tradingPasswrod = tradingPasswrod.trim();
					if (StringUtil.isEmpty(tradingPasswrod)) {
						GlobalUtil.shortToast(mEditText.getContext(), "密码不能为空");
						try {
							Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
							field.setAccessible(true);
							field.set(dialog, false);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}else {
						try {
							Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
							field.setAccessible(true);
							field.set(dialog, true);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}).setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					try {
						Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
						field.setAccessible(true);
						field.set(dialog, true);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}).show();
		} else {
			//弹出提示 去网扎
			DialogUtil.alertDialog(v.getContext(), R.string.no_pay_password_text);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

	}
}
